package cj.web.admin.controllers;

import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import net.paoding.rose.web.annotation.Param;
import net.paoding.rose.web.annotation.Path;
import net.paoding.rose.web.annotation.rest.Get;
import net.paoding.rose.web.annotation.rest.Post;
import net.paoding.rose.web.var.Model;
import net.sf.json.JSONObject;

import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MultipartFile;

import cj.utils.Constants;
import cj.utils.DateUtils;
import cj.utils.ImageUtils;
import cj.utils.ReadConfigProperties;
import cj.utils.ReturnUUID;
import cj.web.admin.dao.AuditStepLogDAO;
import cj.web.admin.dao.ColumnsDAO;
import cj.web.admin.dao.NewsAuditDAO;
import cj.web.admin.dao.NewsDAO;
import cj.web.admin.dao.NewsVersionDAO;
import cj.web.admin.dao.SubjectDAO;
import cj.web.admin.dao.VoteDAO;
import cj.web.admin.domain.AuditStep;
import cj.web.admin.domain.AuditStepConfig;
import cj.web.admin.domain.AuditStepLog;
import cj.web.admin.domain.Columns;
import cj.web.admin.domain.News;
import cj.web.admin.domain.NewsVersion;
import cj.web.admin.domain.Subject;
import cj.web.constants.AuditStepAgreeEnum;
import cj.web.constants.MemuEnum;
import cj.web.constants.NewsCheckStatus;
import cj.web.constants.NewsLabelEnum;
import cj.web.constants.NewsReleaseStateEnum;
import cj.web.constants.NewsTypeEnum;
import cj.web.login.controllers.BaseController;

@Path("/newsAudit")
public class NewsAuditController extends BaseController {
	@Autowired
	private NewsAuditDAO newsAuditDao;
	@Autowired
	private ColumnsDAO columnsDao;
	@Autowired
	private NewsDAO newsDAO;
	@Autowired
	private AuditStepLogDAO auditStepLogDao;
	@Autowired
	private NewsVersionDAO newsVersionDao;
	@Autowired
	private SubjectDAO subjectDAO;
	@Autowired
	private VoteDAO voteDao;
	
	@Get("show")
	public String show(Model model, HttpServletRequest request){
		List<Columns> columnslis = columnsDao.queryByAccountForColumns(returnSessionObj(request).getAccount());//根据账号获取栏目
		model.add("Columnslis",columnslis);

		model.add("NewsType",EnumSet.allOf(NewsTypeEnum.class));//新闻类型
		model.add("CheckStatus",EnumSet.allOf(NewsCheckStatus.class));//审核状态
		model.add("ReleaseStatus",EnumSet.allOf(NewsReleaseStateEnum.class));//发布状态
		//MemuEnum
        model.add("MemuEnum",MemuEnum.lkgwddwsh);
		return "/views/audit/newsAuditList.vm";
	}
	
	@Post("getList")
    public String getList(News news, HttpServletRequest request){
		int userId = returnSessionObj(request).getId();
		List<Map> arr = newsAuditDao.getNewList(userId,news.getStart(),news.getLength(),news.getTitle());
		
		for(Map rep:arr)
		{
			AuditStep obj = newsAuditDao.queryNewsCurrentAuditStep(Integer.parseInt(rep.get("id").toString()));
			if(obj!=null){
				int StepBegin = obj.getStepBegin();
				
				if(StepBegin==0){
					rep.put("currentAuditStep", "二审未审核");
				}else if(StepBegin==1){
					rep.put("currentAuditStep", "三审未审核");
				}else{
					rep.put("currentAuditStep", "一审未审核");
				}
				
			}else{
				rep.put("currentAuditStep", "一审未审核");
			}
		}
		
		JSONObject jo = new JSONObject();
		
		int size = newsAuditDao.getNewListSize(userId, news.getTitle());
		
		jo.put("data", arr);
		jo.put("draw", news.getDraw());
		jo.put("recordsTotal", size);
		jo.put("recordsFiltered", size);
		
		return "@" + jo.toString();
	}
	
	//审核
	@Get("audit")
	public String auditById(Model model,@Param("id") int id,@Param("stepBegin") int stepBegin,HttpServletRequest request){
		News news = newsDAO.queryById(id);
		
		List<Columns> columnslis = columnsDao.queryByAccountForColumns(returnSessionObj(request).getAccount());
		
		model.add("Columnslis",columnslis);
		if (columnslis != null && columnslis.size() > 0) {
			List<Integer> colIds = new ArrayList<Integer>();
			for (Columns col : columnslis) {
				colIds.add(col.getId());
			}
			if(colIds.size() > 0){
				List<Subject> subjects = subjectDAO.queryByColIds(colIds);
				model.add("Subjects",subjects);
			}
		}
		
		model.add("Columnslis",columnslis);
		model.add("NewsType",EnumSet.allOf(NewsTypeEnum.class));//新闻类型
		
		if(news!=null){
			news.setReleaseAt(DateUtils.getMinusTime(news.getReleaseAt(), DateUtils.DATE_FULL_STR, 0));
			model.add("obj", news);
		}
		
		//MemuEnum
		model.add("NewsLabelEnum",EnumSet.allOf(NewsLabelEnum.class));//新闻lable
        model.add("MemuEnum",MemuEnum.lkgwddwsh);
        model.add("stepBegin",stepBegin);
        
        List<AuditStepConfig> auditStepObjs = newsAuditDao.getAuditConfigByXYStepBegin(stepBegin);
        model.add("auditStepObjs",auditStepObjs);
        
        List<AuditStepLog> auditStepLog = auditStepLogDao.queryByNewsId(id);
        for(AuditStepLog obj:auditStepLog)
		{
			obj.setCreateAt(DateUtils.getMinusTime(obj.getCreateAt(), DateUtils.DATE_FULL_STR, 0));
			obj.setUpdateAt(DateUtils.getMinusTime(obj.getUpdateAt(), DateUtils.DATE_FULL_STR, 0));
		}
        model.add("auditStepLog",auditStepLog);
        
        //投票
        List<Map> votes = voteDao.vldtVote();
        model.add("Votes", votes);
		return "/views/audit/newsAuditEdit.vm";
	}
	
	@Get("infor")
	public String inforById(Model model,@Param("id") int id,HttpServletRequest request){
		
		AuditStepLog auditStepLog = auditStepLogDao.queryById(id);
		model.add("auditStepLog",auditStepLog);
		
		NewsVersion news = newsVersionDao.queryByAuditStepLogId(id);
		if(news!=null){
			news.setReleaseAt(DateUtils.getMinusTime(news.getReleaseAt(), DateUtils.DATE_FULL_STR, 0));
			model.add("obj", news);
		}
		
		List<Columns> columnslis = columnsDao.queryByAccountForColumns(returnSessionObj(request).getAccount());
		model.add("Columnslis",columnslis);
		
		model.add("NewsType",EnumSet.allOf(NewsTypeEnum.class));//新闻类型
		//MemuEnum
        model.add("MemuEnum",MemuEnum.lkgwddwsh);

        return "/views/audit/newsAuditInfor.vm";
	}
	
	//审核操作
	@Post("update")
	public String updateById(News news,HttpServletRequest request,@Param("stepBegin") int stepBegin,
			@Param("isAgree") int isAgree,@Param("refuseStepBegin") int refuseStepBegin,@Param("memo") String memo){
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		news.setUpdateAt(DateUtils.getNowTime());
		news.setUpdateUser(returnSessionObj(request).getAccount());
		
		try {
			if(isAgree==AuditStepAgreeEnum.AGREE.getValue()){
				//审核同意
				JSONObject objson = returnYesAudit(news.getId(), request,stepBegin,memo);
				//判断是否操作成功
				String returnFlag = objson.get("returnFlag").toString();
				if(Constants.returnObj.returnFlag_true.equals(returnFlag))
					//判断是否操作成功
				{
					newsDAO.updateNoUpStatus(news);
				}
			}
			else if(isAgree==AuditStepAgreeEnum.REFUSE.getValue()){
				//审核拒绝
				JSONObject objson = returnNoAudit(news.getId(), request,stepBegin,refuseStepBegin,memo);
				//判断是否操作成功
				String returnFlag = objson.get("returnFlag").toString();
				if(Constants.returnObj.returnFlag_true.equals(returnFlag))
					//判断是否操作成功
				{
					newsDAO.updateNoUpStatus(news);
				}
			}
			
		} catch (Exception e) {
			jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
		}
		
		return "@" + jo.toString();
		
	}
	
	@Post("upload")
	public String upload(@Param("uploadimage") MultipartFile file,HttpServletRequest request) {
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		// 判断文件是否为空  
        if (!file.isEmpty()) {  
            try {  
                // 文件保存路径  
            	String path = ReadConfigProperties.getValue("uploadFilePath");
            	//判断文件是否存在，不存在创建文件
            	Map rep = ReturnUUID.getFolder(path);
            	path = rep.get("allpath").toString();//所在的全路径
            	//文件名
                String fileName =  ReturnUUID.getName(file.getOriginalFilename()); 
                // 转存文件  
                file.transferTo(new File(path+"/"+fileName));  
                
                jo.put("filePath", rep.get("filepath")+"/"+fileName);
                
                //扩展名(类似:.gif)
                String kzm = ReturnUUID.getFileExt(fileName);
                
                if(!imgkzm.toLowerCase().equals(kzm.toLowerCase())){
                	//扩展名  不为gif
                	ImageUtils.scale3(path+"/"+fileName, path+"/y_"+fileName, 460, 640);// 按比例压缩,做适当截取
                    
                    ImageUtils.scale3(path+"/"+fileName, path+"/l_"+fileName, 368, 640);// 按比例压缩,做适当截取
                    
                    ImageUtils.scale2(path+"/l_"+fileName, path+"/s_"+fileName, 368, 640, true);//缩率图		750*432
                    
                    ImageUtils.scale2(path+"/y_"+fileName, path+"/ss_"+fileName, 130, 181, true);//缩率图		181*130
                    
                    ImageUtils.scale2(path+"/y_"+fileName, path+"/sss_"+fileName, 165, 230, true);//缩率图	230*165
                }
                
            } catch (Exception e) {  
                e.printStackTrace();  
                jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
            }  
        } 
		
		return "@"+jo.toString();
    }
	
	/**
	 * 同意
	 * @param newsId
	 * @param request
	 * @return
	 */
	private JSONObject returnYesAudit(int newsId, HttpServletRequest request,int stepBegin,String memo)
	{
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		//查询审核记录
		List<Map> obj = newsAuditDao.getNewObjByNewsId(newsId);
		
		if(obj!=null)
		{
			//审核用户ID
			int userId = returnSessionObj(request).getId();
			//查询审核人员
			AuditStep auditStep = newsAuditDao.queryAuditStepById(userId, newsId, stepBegin);
			//审核结束步骤
			if(auditStep!=null)
			{
				int stepEnd = auditStep.getStepEnd();
				//更新审核记录
				newsAuditDao.updateAuditStep(auditStep.getId(),AuditStepAgreeEnum.AGREE.getValue(),memo);
				createAuditStepLog(auditStep, AuditStepAgreeEnum.AGREE.getValue(), memo, "", request);
				//是否存审核记录
				AuditStepConfig auditObj = newsAuditDao.getAuditConfigByStepBegin(stepEnd);
				
				if(auditObj==null){
					int releaseState = NewsReleaseStateEnum.YFB.getValue();//发布状态 - 已发布
					int status = NewsCheckStatus.SHTG.getValue();//审核状态 - 审核通过
					
					//更新新闻审核状态与发布状态记录
					newsAuditDao.updateNewsById(newsId, releaseState, status);
				}
				
				//查询出审核人员列表  < stepBegin deleteFlag=1
				List<AuditStep> auditStepObjs = newsAuditDao.queryAuditStepXYById(newsId, stepBegin);
				
				for(AuditStep auditStepObj:auditStepObjs)
				{
					//跳过审核步骤
					newsAuditDao.updateAuditStep(auditStepObj.getId(),"审核同意跳过");
				}
			}
			else
			{
				jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
				jo.put("returnCode", Constants.returnObj.returnCode.code_2);
			}
		}
		return jo;
	}
	
	/**
	 * 拒绝
	 * @param newsId
	 * @param request
	 * @return
	 */
	private JSONObject returnNoAudit(int newsId, HttpServletRequest request,int stepBegin,int refuseStepBegin,String memo)
	{
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		List<Map> obj = newsAuditDao.getNewObjByNewsId(newsId);
		
		if(obj!=null)
		{
			int userId = returnSessionObj(request).getId();
			
			AuditStep auditStep = newsAuditDao.queryAuditStepById(userId, newsId, stepBegin);
			
			if(auditStep!=null)
			{
				//当前步骤拒绝	>>deleteFlag=0
				newsAuditDao.updateAuditStep(auditStep.getId(),AuditStepAgreeEnum.REFUSE.getValue(),memo);
				
				String descs = "审核退回至";
				if(refuseStepBegin==-1){
					descs+="草稿箱";
				}else{
					AuditStepConfig refuseStep = newsAuditDao.getAuditConfigByStepBegin(refuseStepBegin);
					descs+=refuseStep.getName();
				}
				createAuditStepLog(auditStep, AuditStepAgreeEnum.REFUSE.getValue(), memo, descs, request);
				
				//查询出审核人员列表
				List<AuditStep> auditStepObjs = newsAuditDao.queryAuditStepById(newsId);
				
				for(AuditStep auditStepObj:auditStepObjs)
				{
					//跳过审核步骤
					newsAuditDao.updateAuditStep(auditStepObj.getId(),"审核拒绝跳过");
				}
				
				if(refuseStepBegin==-1)
					//退回草稿箱
				{
					int releaseState = NewsReleaseStateEnum.CAOGAO.getValue();//发布状态 - 草稿
					int status = NewsCheckStatus.WTJ.getValue();//审核状态 - 未提交
					newsAuditDao.updateNewsById(newsId, releaseState, status);
				}
				else
					//退回至某一步骤
				{
					//创建审核步骤
					List<AuditStepConfig> objls = newsAuditDao.getAuditConfigByDYStepBegin(refuseStepBegin-1);
					
					createAuditStep(newsId, request,objls);
				}
			}
			else
			{
				jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
				jo.put("returnCode", Constants.returnObj.returnCode.code_2);
			}
		}
		return jo;
	}
	
	/**
	 * 创建审核记录
	 * @param news		新闻Obj
	 * @param request	http操作对象
	 */
	private void createAuditStep(int newsId,HttpServletRequest request,List<AuditStepConfig> objls)
	{
		//创建审核记录
		for(AuditStepConfig obj:objls){
			
			AuditStep auditStep = new AuditStep();
			auditStep.setNewsId(newsId);
			auditStep.setStepBegin(obj.getStepBegin());
			auditStep.setStepEnd(obj.getStepEnd());
			auditStep.setCreateUser(returnSessionObj(request).getAccount());
			auditStep.setUpdateUser(returnSessionObj(request).getAccount());
			auditStep.setUserId(obj.getUserId());
			auditStep.setName(obj.getName());
			auditStep.setIsAgree(AuditStepAgreeEnum.DDCZ.getValue());
			auditStep.setMemo("");
			newsAuditDao.createAuditStep(auditStep);
		}
	}
	
	/**
	 * 创建Log
	 * @param auditStep		审核人员对象
	 * @param isAgree		是否同意
	 * @param memo			审核人员备注
	 * @param descs			Log操作描述
	 * @param request		HttpServletRequest
	 */
	private void createAuditStepLog(AuditStep auditStep,int isAgree,String memo,String descs,HttpServletRequest request)
	{
		AuditStepLog auditStepLog = new AuditStepLog();
		auditStepLog.setNewsId(auditStep.getNewsId());
		auditStepLog.setName(auditStep.getName());
		auditStepLog.setStepBegin(auditStep.getStepBegin());
		auditStepLog.setStepEnd(auditStep.getStepEnd());
		auditStepLog.setUserId(auditStep.getUserId());
		auditStepLog.setIsAgree(isAgree);
		auditStepLog.setMemo(memo);
		auditStepLog.setDescs(descs);
		auditStepLog.setCreateUser(returnSessionObj(request).getAccount());
		auditStepLog.setUpdateUser(returnSessionObj(request).getAccount());
		int id = auditStepLogDao.create(auditStepLog);
		
		copy(auditStep.getNewsId(), id);
	}
	
	/**
	 * 新闻复制版本
	 * @param newObject
	 * @param oldObject
	 */
	private void copy(int newsId,int auditStepLogId)
    {
        try
        {
        	NewsVersion newsVersion = new NewsVersion();
        	News news = newsDAO.queryById(newsId);
            BeanUtils.copyProperties(newsVersion, news);
            
            newsVersion.setId(null);
            newsVersion.setNewsId(news.getId());
            newsVersion.setAuditStepLogId(auditStepLogId);
            newsVersionDao.create(newsVersion);
        }
        catch (IllegalAccessException e)
        {
            e.printStackTrace();
        }
        catch (InvocationTargetException e)
        {
            e.printStackTrace();
        }
    }
}